package com.eurasia.assignment.infrastructure.client.hoj.auth;

import com.eurasia.assignment.service.port.out.FetchHOJAuthorizationPort;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Log4j2
public class HOJAuthClientAdapter implements FetchHOJAuthorizationPort {

    private final HOJLoginFeignClient hojLoginFeignClient;

    // 从 application.yml 文件读取 HOJ_USERNAME 和 HOJ_PASSWORD
    // 如果环境变量中存在，则优先使用环境变量中的值
    @Value("${target.service.auth.username}")
    private String username;
    @Value("${target.service.auth.password}")
    private String password;

    @Override
    public String fetchHOJAuthorization() {

//        log.debug("HOJ_USERNAME: " + System.getenv("HOJ_USERNAME"));
        ResponseEntity<String> response = hojLoginFeignClient.login(LoginRequest.builder()
                .username(username)
                .password(password)
                .build());

        return response.getHeaders().getFirst("authorization");
    }
}
